package engine.j2d;



import org.lwjgl.opengl.GL11;

import engine.system.*;

public class Image 
{
	private Texture texture;
	private float x;
	private float y;
	private int width;
	private int height;
	private float tWidth;
	private float tHeight;
	private float tOffsetX =0;
	private float tOffsetY=0;
	private String ref;
	protected Image() {
		// hide constructor
	}
	public Image(String ref)
	{
		this(ref,0,0);
	}
	public Image(String ref,float x,float y)
	{
		texture= ToolKit.getTexture(ref);
		this.x=x;
		this.y=y;
		this.ref=ref;
		if (texture != null) 
		{
			width = texture.getImageWidth();
			height = texture.getImageHeight();
			tWidth = texture.getWidth();
			tHeight = texture.getHeight();
		}
	}
	public void draw(float xpos,float ypos)
	{
		texture.bind();
		bindColor();
		drawGL(xpos, ypos);
	}
	public void draw(float xpos,float ypos,Color col)
	{
		texture.bind();
		GL11.glColor3f(col.r, col.g, col.b);
		drawGL(xpos, ypos);
	}
	private void drawGL(float xpos,float ypos)
	{
		GL11.glTranslatef(x+xpos, y+ypos, 0);	
        GL11.glBegin(GL11.GL_QUADS); 
        {
        	GL11.glTexCoord2f(tOffsetX, tOffsetY);				GL11.glVertex2f(0, 0);
        	GL11.glTexCoord2f(tOffsetX,tHeight+tOffsetY);		GL11.glVertex2f(0, height);
        	GL11.glTexCoord2f(tWidth+tOffsetX,tHeight+tOffsetY);GL11.glVertex2f(width,height);
        	GL11.glTexCoord2f(tWidth+tOffsetX, tOffsetY);		GL11.glVertex2f(width, 0);
        }
        GL11.glEnd();
        GL11.glLoadIdentity();
	}
	public void bind()
	{
		texture.bind();
	}
	private void bindColor()
	{
		Color f= Color.WHITE;
		f.bind();
	}
	public Image getSubImage(int _x,int _y,int _width,int _height) 
	{		
		float newTOffsetX = ((_x / (float) this.width) * tWidth) + tOffsetX;
		float newTOffsetY = ((_y / (float) this.height) * tHeight) + tOffsetY;
		float newTWidth = ((_width / (float) this.width) * tWidth);
		float newTHeight = ((_height / (float) this.height) * tHeight);		
		Image sub = new Image();
		sub.texture = this.texture;
		sub.tOffsetX = newTOffsetX;
		sub.tOffsetY = newTOffsetY;
		sub.tWidth = newTWidth;
		sub.tHeight = newTHeight;
		
		sub.width = _width;
		sub.height = _height;
		sub.ref = this.ref;
		
		return sub;
	}
	public int getWidth() 
	{
		return width;
	}
	public int getHeight() 
	{
		return height;
	}
}
